package pt.inescid.components.policyengine.heimdall.pdp.base;

import java.util.Vector;

import pt.inescid.components.policyengine.heimdall.base.EventObj;
import pt.inescid.components.policyengine.heimdall.commons.Log;
import pt.inescid.components.policyengine.heimdall.pap.base.CesAggDefinition;

public class CesAggInstance extends SimpleInstance {

	private CesAggDefinition definition = null;
	private CesInstance ces = null;
	private int value = -1;
	
//  ----------------------------------------------------------
//  ------------------------   constructor   ------------------------
//  ----------------------------------------------------------
	public CesAggInstance(CesAggDefinition definition,
			ModelInstance currentModel,
			PolicyInstance currentPolicy) {
		super(definition, currentPolicy);

		CesInstance newCes = new CesInstance(definition, currentModel,
				currentPolicy);
		ces = newCes;
		currentModel.addCes(newCes);
		
		this.definition = definition;
	}

//  ----------------------------------------------------------
//  ------------------------   toString   ------------------------
//  ----------------------------------------------------------
	public String toString() {
		return (super.toString() + "[value=" + value + "]");
	}


//  ----------------------------------------------------------
//  ------------------------   resetEvaluation  ------------------------
//  ----------------------------------------------------------
	public void resetEvaluation(ModelInstance currentModel) {
		
		CesInstance currentCes = currentModel.getCes(
				definition.getDomain().getName(), 
				definition.getCes().getName());
		
		currentCes.resetEvaluation();
	}

//  ----------------------------------------------------------
//  ------------------------   evaluate  ------------------------
//  ----------------------------------------------------------
	public Object evaluate(ModelInstance currentModel, boolean onlyCached) {
		Log.debug(Log.INFO, "Arrived.", "CesAggInstance.evaluate");
		
		CesInstance currentCes = currentModel.getCes(
				definition.getDomain().getName(), 
				definition.getCes().getName());
		Vector allEvents = currentCes.getUnprocessedEvents(
				currentModel, onlyCached);
		int currentValue = currentCes.getValue();
		String eventFieldName = definition.getEventField().getValue();
		for (int i = 0; i < allEvents.size(); i++) {
			EventObj currentEvent = (EventObj) allEvents.elementAt(i);
			int auxValue = ((Integer) currentEvent.getField(
					definition.getEventField().getModelDef().getFieldId(
					eventFieldName)).getValue()).
						intValue();
			currentValue += auxValue;
		};
		currentCes.setValue(currentValue);
		
		return (new Integer(currentValue));
	} // evaluate

}; // SubPolicyExpression
